import axios from 'axios'
import common from './common'

//创建一个axios实例
const api = axios.create({
    baseURL:common.baseUrl,
    timeout:200000
})

//拦截请求 
api.interceptors.request.use(function(config){
    console.log('config>>>>',config);
    //判断缓存中是否有登录信息，有则将用户ID放到请求头中
    const id = localStorage.getItem('userid') || null
    if(id){
        config.headers["user"] = id;
    }
    return config;
},function(error){
    //请求错误做些什么
    return Promise.reject(error);
})
    //  封装get请求
    const get = async (url, data) => {
        const response = await api.get(url, data)
        .then(res => {
            return res
        }).catch(error => {
            console.log( error );
            // errorHandler(error)
            alert(error.response.data.message || '接口报错了，请重试！');
        })
        return response
    }
//封装post请求
const post = async (url,data) =>{
    const response = await api.post(url,data).then(res =>{
        return res
    }).catch(error =>{
        console.log(error.response)
    })
    return response
}
//封装put请求
const put = async (url,data) =>{
    const response = await api.put(url,data).then(res =>{
        return res.data
    }).catch(error =>{
        console.log(error.response)
    })
    return response
}

api.interceptors.request.use(config => {
    
    //    console.log("config", config);
       // 在发送请求之前做些什么
       let data = JSON.parse(localStorage.getItem('userInfo')) || {_id:''}
       config.headers.user=data._id 
      
       console.log('config',config);
       return config;
       
     }, function (error) {
       // 快速获得一个拒绝状态的promise队对象
       return Promise.reject(error);
     });



export {
    get,
    post,
    put
}